import { computed, watch, onMounted } from 'vue';
import { keyboardList } from '@/common/js/keyboard.js';
import { chinesePunctuationToEnglish } from '@/common/utils/index.js';
import { arrGorup } from '@/common/utils/index.js';
import useTyping from './useTyping.js';
export default function(getContent) {
	const {
		seting,
		typing,
		setTyping,
		recordSpeed,
		itemClassName,
		showErrorClass,
		progress,
		accuracyKey,
		accuracyWord,
		courseComplete,
		next,
		queryRect,
		typingSound,
		gameSound
	} = useTyping(getContent, keydownFun, resizeFun);
	seting.mode = 'CNCOPY';
	typing.type = 'CNCOPY';
	typing.offset = {
		top: 0,
		left: 0
	}
	typing.inputText = '';
	typing.showInput = true;
	typing.rowCount = 0;
	typing.scrollTop = [];
	onMounted(() => {
		// 监听并设置滚动条位置
		watch(() => typing.current, async (newVal) => {
			const element = document.getElementById('bd_view');
			const { top: bdTop, left: bdLeft, bottom: bdBottom } = await queryRect('bd');
			// ===计算input的位置 start===
			const { top: itemTop, left: itemLeft } = await queryRect(`input-item-${newVal}`);
			typing.offset.left = `${itemLeft - bdLeft}px`;
			typing.offset.top = `${itemTop - bdTop + element.scrollTop}px`;
			typing.showInput = true;
			// ===计算input的位置 end===
			// ===计算滚动条的位置 start===
			const doScroll = (scrollVal) => {
				let timer = 0;
				let count = 0;
				timer = setInterval(() => {
					element.scrollTop = scrollVal;
					count++;
					if (count >= 10) {
						timer && clearInterval(timer);
					}
				}, 1)
			}
			const rowIndex = Math.floor(typing.current / typing.rowCount);
			if (typeof typing.scrollTop[rowIndex] != 'undefined') {
				doScroll(typing.scrollTop[rowIndex]);
			} else {
				const { bottom: rowBottom } = await queryRect(`item-row-${rowIndex}`);
				if (bdBottom - rowBottom < 0) {
					const v = element.scrollTop - (bdBottom - rowBottom - 50);
					typing.scrollTop[rowIndex] = v;
					doScroll(v);
				} else {
					typing.scrollTop[rowIndex] = element.scrollTop;
				}
			}
			// ===计算滚动条的位置 end===
		}, { immediate: true })
	})
	// 浏览器窗口变化
	function resizeFun() {
		const { courseContentArr, courseContentGroupArr } = getGroupContent();
		typing.content = courseContentArr;
		typing.contentGroup = courseContentGroupArr;
	}
	resizeFun();
	// 获取分组内容
	function getGroupContent() {
		let totalIndex = 0;
		// 1920 一排 36个字
		const zoom = 38 / 1920;
		typing.rowCount = Math.floor(uni.$uv.sys().windowWidth * zoom);
		const courseText = getContent().courseText[0]?.split('');
		let groupArr = arrGorup(courseText ? courseText : [], typing.rowCount);
		groupArr = groupArr.map((subarray, parentIndex) => {
			return subarray.map(char => {
				return { parentIndex, index: totalIndex++, char: char };
			})
		})
		return {
			courseContentArr: groupArr.flat(),
			courseContentGroupArr: groupArr
		}
	}
	// 输入的数据
	const recordInputText = computed((index) => {
		return index => {
			try {
				const arr = typing.record[index];
				return arr[arr.length - 1].text;
			} catch (e) {
				return '';
			}
		}
	})
	// 键盘事件处理
	function keydownFun(e) {
		const find = keyboardList.find(item => item.keyCode == e.keyCode);
		if (find) {
			if (progress.value >= 100) {
				return next(find);
			}
			switch (find.key) {
				case 'Backspace':
					if (typing.current > 0) {
						typing.current--;
						setTyping('back', '');
					}
					typingSound('backspace');
					break;
			}
		}
	}
	// 输入文字
	function inputChange(e) {
		const value = e.detail.value;
		if (value == '') return;
		typing.showInput = false;
		typing.inputText = '';
		let hasError = false;
		for (let i = 0; i < value.length; i++) {
			const text = value[i];
			if (text == typing.content[typing.current].char) {
				setTyping('success', text);
			} else {
				setTyping('error', text);
				hasError = true;
			}
			typing.current++;
		}
		if (hasError) {
			typingSound('error');
		} else {
			typingSound('success');
		}
		if (!typing.startTime) {
			typing.timer = setInterval(() => {
				typing.time++;
				recordSpeed();
			}, 1000)
			typing.startTime = Date.now();
		}
	}
	return {
		typing,
		successRate: accuracyWord,
		progress,
		itemClassName,
		courseComplete,
		inputChange,
		recordInputText
	}
}